package com.example.dbscrew;

import com.example.dbscrew.service.DBService;
import com.example.dbscrew.util.ProgressUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

@SpringBootTest
public class DatabaseProcessor {

    @Resource
    private DBService dbService;

    @Test
    public void contextLoads() {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        try {
            List<String> dbTable = dbService.getDBTable();

            if (dbTable != null && !dbTable.isEmpty()) {
                int totalTables = dbTable.size();
                AtomicInteger processedTables = new AtomicInteger(0);
                CountDownLatch latch = new CountDownLatch(totalTables);

                ExecutorService executor = Executors.newFixedThreadPool(20);

                for (String table : dbTable) {
                    executor.submit(() -> {
                        try {
                            dbService.generateTableDoc(table);
                        } catch (Exception e) {
                            System.err.println("Error generating table: " + table + " - " + e.getMessage());
                        } finally {
                            processedTables.incrementAndGet();
                            ProgressUtil.showProgress(processedTables.get(), totalTables);
                            latch.countDown(); // 每完成一个任务，计数器减一
                        }
                    });
                }

                latch.await(); // 等待所有任务完成
                executor.shutdown();

                // 计算总用时
                long elapsedTime = System.currentTimeMillis() - startTime;
                long seconds = (elapsedTime / 1000) % 60;
                long minutes = (elapsedTime / (1000 * 60)) % 60;
                System.out.printf("总用时: %02dm:%02ds\n", minutes, seconds); // 显示总用时
            } else {
                System.out.println("No tables to process.");
            }
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }


}
